/**
 * Created by apple on 2017/6/10.
 */
var DBFactory = require('../db/mysql_db');
var async = require('async');
var paymentDao = require('../dao/payment');
var adminUserDao = module.exports;
var UserDao = require('../dao/users');
var GlobalVar = require('../global_var');
var Config = require('../config');

adminUserDao.findUser = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    adminUserDao.getSQLAndValue(data, function (sql, value) {
        DBFactory.poolQuery(sql, value,
            function () {
                cb('no collection');
            },
            function (err, result) {
                if (err) {
                    console.log(err);
                    cb(err);
                    return;
                }
                cb(null, result);
            }
        );

    });
}

adminUserDao.getAccounts = function (data,cb) {
    if(!data){
        cb(new Error(500));
        return;
    }
    DBFactory.poolQuery('select uid,account from users where uid in (?)',[data.uids],
        function () {
            cb('no connection');
        },
        function(err, result){
            if(err){
                cb(err);
                console.log(err);
                return;
            }
            cb(null,result);
        }
    );

}

adminUserDao.resetUserPwd = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        connection.query('select app_sid from user_app_new_agent where uid = ?',
            [data.uid],
            function (err, result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }
                if (result.length > 0) {
                    var apps = [];
                    result.forEach(function (o) {
                        apps.push(o.app_sid);
                    })
                    console.log(apps);
                    if (apps.indexOf(data.app_sid) >= 0 || !data.app_sid) {
                        connection.query('update users set password = ? where uid = ?',
                            [data.password, data.uid],
                            function (err, result) {
                                if (err) {
                                    cb(err);
                                    connection.release();
                                    return;
                                }
                                if (result) {
                                    cb(null, result);
                                }
                                connection.release();
                            });
                    } else {
                        cb("该管理员没有权限");//用户没有使用过该系统
                        connection.release();
                    }
                }
            });
    });
}


//根据data确定sql语句以及value
adminUserDao.getSQLAndValue = function (data, cb) {
    var sql;
    var value = [];
    //app_sid需多查一张表
    if (data.app_sid) {

        if (data.vip_sid) {//vip_sid需多查一张表
            sql = 'select a.uid,b.account,b.name from user_app_new_agent a join users b on a.uid=b.uid ' +
                'join user_vip c on a.uid=c.uid and a.app_sid=c.app_sid where a.app_sid = ? and c.vip_sid = ? '
            value.push(data.app_sid, data.vip_sid);

        } else {//查两张
            sql = 'select a.uid,b.account,b.name from user_app_new_agent a join users b on a.uid=b.uid where a.app_sid = ? ';
            value.push(data.app_sid);
        }

        if (data.phoneTail && data.name) {
            sql += 'and b.account like ? and b.name = ? ';
            value.push('%' + data.phoneTail + '%', data.name);
        } else if (data.phoneTail) {
            sql += 'and b.account like ? ';
            value.push('%' + data.phoneTail + '%');
        } else if (data.name) {
            sql += 'and b.name = ? ';
            value.push(data.name);
        }
    } else {
        if (data.vip_sid) {//vip_sid需多查一张表
            sql = 'select a.uid,a.account,a.name from users a join user_vip b on a.uid=b.uid where b.vip_sid = ? '
            value.push(data.vip_sid);

        } else {
            //仅查user
            sql = 'select uid,name,account from users ';
        }

        if (data.phoneTail && data.name) {
            sql += data.vip_sid ? 'and substring(a.account,-4) like ? and a.name = ? ' :
                'where account like ? and name = ? ';
            value.push('%' + data.phoneTail + '%', data.name);
        } else if (data.phoneTail) {
            sql += data.vip_sid ? 'and substring(a.account,-4) like ? ' :
                'where account like ? ';
            value.push('%' + data.phoneTail + '%');
        } else if (data.name) {
            sql += data.vip_sid ? 'and a.name = ? ' :
                'where name = ? ';
            value.push(data.name);
        }


    }

    var pageNum = data.pageNum ? data.pageNum : 10;
    var page = data.page ? data.page : 1;
    sql += 'limit ' + (page - 1) * pageNum + ',' + pageNum;

    cb(sql, value);
}

adminUserDao.setAgentLvl = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {//先查是否存在该代理
                connection.query('select score from app_agent where app_sid = ? and lvl = ? and status = 1', [data.app_sid, data.lvl], function (err, result) {
                    var agentInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(err, agentInfo);
                });
            },

            function (agentInfo, callback) {
                if (!agentInfo) {
                    callback('代理设置有误!', null);
                    return;
                }
                connection.query('update user_app_new_agent set agent_lvl = ?,score = ? where uid = ? and app_sid = ?', [data.lvl, agentInfo.score, data.uid, data.app_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败', null);
                            console.log('插入app_agent表失败');
                            return;
                        }
                        callback(null, '成功');
                    });
            },

            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }//到这里说明修改user_app_new_agent表成功，log下
                var adminLog = {
                    uid: data.uid,
                    adm_uid: data.adm_uid,
                    type: 4,
                    account: data.account,
                    detail: '管理员设置用户代理级别为：' + data.lvl
                };
                connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}


adminUserDao.delUserVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query('delete from user_vip where uid = ? and app_sid = ? and vip_sid = ?', [data.uid, data.app_sid, data.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败', null);
                            console.log('删除权限时操作user_vip表失败');
                            return;
                        }
                        callback(null, '成功');
                    });
            },

            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }//到这里说明修改user_vip表成功，log下
                var adminLog = {
                    uid: data.uid,
                    adm_uid: data.adm_uid,
                    type: 4,
                    account: data.account,
                    detail: '管理员删除用户VIP:' + data.app_sid + ':' + data.vip_sid
                };
                connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });
    });
}

adminUserDao.delUsersVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query('delete from user_vip where uid in ('+ data.uids +') and app_sid = ? and vip_sid = ?', [data.app_sid, data.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败', null);
                            console.log('删除权限时操作user_vip表失败');
                            return;
                        }
                        callback(null, '操作成功');
                    });
            },
            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }
                //查找被删除权限的账号
                connection.query('select GROUP_CONCAT(account) accounts from users where uid in ('+ data.uids +')',[],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        callback(null,result[0].accounts);
                    });
            },
            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }
                //到这里说明修改user_vip表成功，log下
                connection.query('delete from vip_log where client_account in (?) and app_sid = ? and vip_sid = ?', [res,data.app_sid, data.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }

                        if (result.affectedRows <= 0) {
                            callback('操作失败', null);
                            console.log('删除权限时操作user_vip表失败');
                            return;
                        }
                        callback(null, '操作成功');
                    });
            },
            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }
                //到这里说明修改user_vip表成功，log下
                var sql = 'insert into admin_log ('+ adminLogsColumnNames() +') values ? ';
                var adminLogs = getDelAdminLogsInfo(data);
                console.log(adminLogs);
                connection.query(sql, [adminLogs], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });
    });
}

//添加用户
adminUserDao.addUser = function (data, cb) {
    if (!data) return cb(new Error(500));

    DBFactory.getConnection(function (error, connection) {//使用transaction创建新用户
        if (error) {
            cb(error);
        } else {
            async.waterfall([
                // 开始Transaction
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },

                //验证account
                function (callback) {
                    connection.query("select * from users where account = ? limit 1", [data.account], function (err, result) {
                        var userOld = (result && result.length > 0) ? result[0] : undefined;
                        callback(err, userOld);
                    });
                },

                //插入/查询users表
                function (userOld, callback) {
                    if (userOld) {//用户已注册
                        callback('用户已被注册！', false, null);
                    } else {//新用户
                        var user = {
                            status: 1,
                            account: data.account,
                            name: data.name,
                            password: data.password
                        };
                        //引流平台类型：ios/android/pc/web
                        if (data.source) {
                            user.reg_source = data.source;
                        }
                        //引流产品：benliu/huoma
                        user.reg_app = data.app_sid;
                        connection.query("insert into users set ?", user,
                            function (err, result) {
                                var uid = (result) ? result.insertId : undefined;
                                callback(err, uid);
                            });
                    }
                },
                function (uid, callback) {
                    if (uid) {
                        data.uid = uid;
                        data.detail = '注册成功！';
                        if (data.recommendCode) {
                            data.recommendUid = codeToUid(data.recommendCode);
                            var info = {};
                            info.uid = data.uid;
                            info.app_sid = data.app_sid;
                            info.recommendUid = uid;
                            UserDao.isVip(data, function (e, result) {
                                if (e) {
                                    console.log(e);
                                    data.recommendInfo = '推荐码不正确！';
                                    delete data.recommendUid;
                                }
                                delete data.recommendCode;
                                if (result) {
                                    data.recommendInfo = '添加推荐人成功！';
                                    data.recommenderAccount = result.account;
                                    callback(null, data);
                                } else {
                                    data.recommendInfo = '推荐人必须为vip用户或推荐码不正确！';
                                    delete data.recommendUid;
                                    callback(null, data);
                                }
                            });

                        } else {
                            callback(null, data);
                        }
                    }
                },

                function (data, callback) {
                    if (data) {
                        UserDao.addAgent(data, function (e, result) {
                            if (e) {
                                data.detail += '，用户关联产品表失败!';
                            }
                            callback(null, data);
                        });
                    }
                },

                function (data, callback) {
                    var adminLog = {
                        uid: data.uid,
                        adm_uid: data.adm_uid,
                        type: 4,
                        account: data.adm_account,
                        detail: '管理员新增用户，account ：' + data.account
                    };
                    connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            delete data.adm_uid;
                            callback(null, true, data);
                        } else {
                            callback('操作失败', null);
                            console.log('操作admin_log表失败')
                        }
                    });

                }
            ], function (DbErr, isSuccess, uidOrInfo) {
                if (DbErr) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else if (!isSuccess) {
                    connection.rollback(function () {
                        connection.release();
                        cb(DbErr);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, uidOrInfo);
                        }
                    });
                }
            });
        }
    });
}


//添加用户vip
adminUserDao.addUserVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query('SELECT account FROM users where uid = ? ', [data.uid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var userInfo = (result && result[0]) ? result[0] : undefined;
                        if (!userInfo) {
                            callback('用户不存在');
                            return;
                        }
                        callback(null, userInfo);
                    });
            },

            function (userInfo, callback) {

                var vipInfo = {
                    uid: data.uid,
                    account: userInfo.account,
                    app_sid: data.itemInfo.app_sid,
                    vip_sid: data.itemInfo.vip_sid,
                    end_time: data.expireDate,
                    vip_type: data.itemInfo.vip_type
                };


                vipInfo.lvl = data.vipInfo ? data.vipInfo.lvl : data.itemInfo.lvl;
                vipInfo.created_time = data.vipInfo ? data.vipInfo.created_time : new Date();

                if (data.vipInfo) {//如果是续费 且是积分、押金类型，要加。
                    if (vipInfo.vip_type == 1 || vipInfo.vip_type == 2) {
                        vipInfo.lvl += data.itemInfo.lvl;
                    }
                }
                console.log(vipInfo);
                connection.query('replace into user_vip set ? ', [vipInfo],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败', null);
                            console.log('添加权限时操作user_vip表失败');
                            return;
                        }
                        callback(null, vipInfo);
                    });
            },

            function (vipInfo, callback) {
                if (!vipInfo) {
                    callback('操作失败', null);
                    return;
                }//到这里说明修改user_vip表成功，log下
                var adminLog = {
                    uid: data.uid,
                    adm_uid: data.adm_uid,
                    type: 4,
                    account: data.adm_account,
                    detail: '管理员添加用户VIP: app_sid:' + data.itemInfo.app_sid + ',vip_sid:' + data.itemInfo.vip_sid
                };
                connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}

adminUserDao.addUsersVipFromPD = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },
            function (callback) {
                //批量添加用户信用等级
                data.userVipInfo = {
                    uids: data.uids,
                    app_sid: data.app_sid,
                    vip_sid: 'creditLvl',
                    end_time: '2088-01-01 00:00:00',
                    lvl: 102
                };
                adminUserDao.addUsersVip(data, function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, result);
                });
            },
            function (userInfo, callback) {
                //批量添加用户积分
                data.userVipInfo.vip_sid = 'moneyPoint';
                data.userVipInfo.lvl = data.moneyPoint;
                data.userVipInfo.end_time = '2088-01-01 00:00:00';
                adminUserDao.addUsersVip(data, function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, result);
                    console.log(result);
                });
            },
            // 批量给上级代理赋予5000个财富积分，没有财富积分的就算了
            function (userInfo, callback) {
                var sql = 'select a.uid, a.account,a.recommender,b.lvl' +
                    ' from user_app_new_agent a LEFT JOIN user_vip b ON a.app_sid = b.app_sid and a.recommender = b.account' +
                    ' where a.uid in ('+data.uids+') and a.app_sid = ? and b.vip_sid = "moneyPoint"';
                connection.query(sql, [data.app_sid], function(err, result) {
                    if(err) {
                        callback(err);
                    } else {
                        callback(null,result);
                    }
                });
                
            },
            function (recs, callback) {
                if(recs && recs.length > 0){
                    var recO = {};
                    var rec = [];
                    recs.forEach(function (o) {
                        if(!recO.hasOwnProperty(o.recommender)){
                            rec.push(o.recommender);
                            recO[o.recommender] = 5000 + o.lvl;
                        }else {
                            recO[o.recommender] += 5000;
                            o.lvl += 5000;
                        }
                    })
                    var sql = 'UPDATE user_vip'
                        + ' set lvl = CASE account';
                    for(var recommender in recO){
                        sql += ' WHEN ' + recommender + ' THEN ' + recO[recommender];
                    }
                    sql += ' END';
                    sql += ' where app_sid = ? and account in (?) and vip_sid = ? ';
                    console.log(sql);
                    console.log(recs);
                    connection.query(sql, [data.app_sid,rec,'moneyPoint'], function(err, result) {
                        if(err) {
                            callback(err);
                        } else {
                            if(result.affectedRows > 0) {
                                var sql2 = 'insert into vip_log (' + recVlogColumnNames() + ') VALUES ?';
                                var vips = getRecVlogs(recs, data);
                                connection.query(sql2, [vips], function(e, r) {
                                    if(e) {
                                        callback(e);
                                    } else {
                                        if(r.affectedRows > 0){
                                            callback(null,true);
                                        }else {
                                            callback('记录认证奖励积分失败');
                                            return;
                                        }
                                    }
                                });
                            } else {
                                callback(null, true);
                            }
                        }
                    });
                }else {
                    callback(null,true);
                }
            },
            function (isok, callback) {
                //批量添加用户一个月的上单权限
                data.userVipInfo.vip_sid = 'publishGoods';
                data.userVipInfo.lvl = 1;
                data.isUpdate = 1;
                data.userVipInfo.end_time = '2088-01-01 00:00:00';
                adminUserDao.addUsersVip(data, function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, result);
                });
            },
        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });
    });
}

function recVlogColumnNames() {
    return "`seller_account`,`client_account`,`vip_name`,`vip_type`,`lvl`," +
        "`duration`,`cost`,`comment`,`original_vip_name`,`price`,`num`," +
        "`app_sid`,`vip_sid`,`original_vip_expire`,`original_lvl`,`sign`,`exInfo`";
}

function getRecVlogs(recs, data) {
    var viplogs = [];
    recs.forEach(function (o) {
        viplogs.push(recVlogColumn(o, data));
    })
    return viplogs;
}

function recVlogColumn(o, data) {
    o.account = o.account.length >= 11 ?  o.account.substr(0,3) + '****' + o.account.substr(7,4) : '';
    var viplogs = [];
    viplogs.push('srv');
    viplogs.push(o.recommender);
    viplogs.push('邀请认证奖励5000积分');//vip_name
    viplogs.push(1);//vip_type
    viplogs.push(5000);//获得的积分lvl
    viplogs.push(0);
    viplogs.push(0);
    viplogs.push('邀请'+ o.account +'认证奖励5000积分');
    viplogs.push('平台奖励积分');
    viplogs.push(0);//price
    viplogs.push(1);//num
    viplogs.push(data.app_sid);
    viplogs.push('moneyPoint');
    viplogs.push('2088-01-01 00:00:00');
    viplogs.push(o.lvl);
    viplogs.push(0);
    viplogs.push(o.uid);
    return viplogs;
}

adminUserDao.delUsersVipFromPD = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },
            function (callback) {
                //批量删除用户信用等级
                data.vip_sid = 'creditLvl';
                adminUserDao.delUsersVip(data, function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, result);
                });
            },
            function (userInfo, callback) {
                //批量删除用户积分
                data.vip_sid = 'moneyPoint';
                adminUserDao.delUsersVip(data, function (err, result) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    callback(null, result);
                    console.log(result);
                });
            },
        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });
    });
}

//批量添加用户vip
adminUserDao.addUsersVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    var userInfos = [];
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                //检查是否所有uid都有注册过了
                connection.query('SELECT uid,account FROM users where uid in (' + data.userVipInfo.uids + ')', [],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var len = data.userVipInfo.uids.split(',').length;
                        if (result && result.length > 0) {
                            if (result.length == len) {
                                userInfos = result;
                                callback(null, result);
                            } else {
                                callback('操作失败，有些uid是虚假的');
                            }
                        } else {
                            callback('操作失败，所有uid都没有操作的权限');
                        }
                    });
            },
            function (userInfo, callback) {
                //检查是否有该权限
                connection.query('SELECT type,top_lvl FROM app_vip where app_sid = ? and sid = ? ', [data.userVipInfo.app_sid, data.userVipInfo.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var vipInfo = (result && result[0]) ? result[0] : undefined;
                        if (!vipInfo) {
                            callback('会员项目不存在');
                            return;
                        }
                        data.vip_type = vipInfo.type;
                        if (vipInfo.type != 0) {
                            data.endTime = null;
                        }
                        if (data.userVipInfo.lvl > vipInfo.top_lvl) {
                            callback('等级超过上限');
                            return;
                        }
                        callback(null, vipInfo);
                    });
            },
            function (vipInfo, callback) {
                //查看uid是否应经有该vip
                if(data.isUpdate){
                    callback(null,true);
                    return;
                }
                connection.query('SELECT * FROM user_vip where uid in (' + data.userVipInfo.uids + ') and app_sid = ? and vip_sid = ? ', [data.userVipInfo.app_sid, data.userVipInfo.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if (result && result.length > 0) {
                            callback('有部分uid已经有' + data.userVipInfo.vip_sid + '权限');
                            return;
                        }
                        callback(null, true);
                    });
            },
            function (isOK, callback) {
                //增加权限
                var sql = 'replace into user_vip (' + uservipsColumnNames() + ') VALUES ?';
                var userVips = getUserVipsInfo(userInfos, data);
                console.log(userVips);
                connection.query(sql, [userVips], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, userVips);
                        return;
                    }
                    callback('操作失败');
                });
            },

            //vip_log表的记录
            function (userVipInfo, callback) {
                if (!userVipInfo) {
                    callback('操作失败');
                    return;
                }
                var sql = 'insert into vip_log (' + vipLogsColumnNames() + ') VALUES ?';
                var vipLogs = getVipLogsInfo(userInfos, data);
                connection.query(sql, [vipLogs], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows == userInfos.length) {
                        callback(null, '继续');
                        return;
                    }
                    callback('操作失败');
                });
            },

            //admin_log表的记录
            function (vipInfo, callback) {
                if (!vipInfo) {
                    callback('操作失败', null);
                    return;
                }
                //到这里说明修改user_vip表成功，log下
                var sql = 'insert into admin_log (' + adminLogsColumnNames() + ') VALUES ?';
                var adminLogs = getAdminLogsInfo(userInfos, data);
                connection.query(sql, [adminLogs], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows == userInfos.length) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败');
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}

//(添加或)修改用户vip（单个）
adminUserDao.updateUserVip = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                connection.query('SELECT account FROM users where uid = ? ', [data.userVipInfo.uid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var userInfo = (result && result[0]) ? result[0] : undefined;
                        if(!userInfo){
                            callback('用户不存在');
                            return;
                        }
                        data.account = userInfo.account;
                        callback(null, userInfo);
                    });
            },

            function (userInfo,callback) {
                connection.query('SELECT type,top_lvl FROM app_vip where app_sid = ? and sid = ? ', [data.userVipInfo.app_sid,data.userVipInfo.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var vipInfo = (result && result[0]) ? result[0] : undefined;
                        if(!vipInfo){
                            callback('会员项目不存在');
                            return;
                        }
                        data.vip_type = vipInfo.type;
                        if(data.userVipInfo.lvl > vipInfo.top_lvl){
                            callback('等级超过上限');
                            return;
                        }
                        callback(null,vipInfo);
                    });
            },

            function (vipInfo,callback) {

                connection.query('SELECT * FROM user_vip where uid = ? and app_sid = ? and vip_sid = ? ', [data.userVipInfo.uid,data.userVipInfo.app_sid,data.userVipInfo.vip_sid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        var userVipInfo = (result && result[0]) ? result[0] : undefined;
                        callback(null,userVipInfo);
                    });
            },



            function (userVipInfo,callback) {

                data.changeLvl = userVipInfo && userVipInfo.lvl ? Math.abs((userVipInfo.lvl - data.userVipInfo.lvl)) :
                    data.userVipInfo.lvl;
                if (!data.changeLvl) data.changeLvl = 0;
                data.original_lvl = userVipInfo ? userVipInfo.lvl : 0;
                data.original_vip_expire = userVipInfo ? userVipInfo.end_time : null;
                data.vip_expire = data.userVipInfo.end_time;
                if(userVipInfo){//如果存在，替换要替换的
                    data.sign = userVipInfo.lvl < data.userVipInfo ? 1 : 0;


                    //如果存在，替换要替换的
                    for(var key in data.userVipInfo) {
                        userVipInfo[key] = data.userVipInfo[key];

                    }
                }else {//如果不存在，直接用新的

                    data.sign = 0;

                    userVipInfo = data.userVipInfo;//基本的先附上
                    userVipInfo.vip_type = data.vip_type;
                    userVipInfo.account = data.account;
                    userVipInfo.created_time = new Date();
                }

                connection.query('REPLACE INTO user_vip set ? ', [userVipInfo], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,userVipInfo);
                        return;
                    }
                    callback('操作失败');
                });
            },

            //vip_log表的记录
            function (userVipInfo,callback) {
                if(!userVipInfo){
                    callback('操作失败');
                    return;
                }
                var vipLogInfo = {
                    seller_account: 'srv',
                    client_account: data.account,
                    vip_name: '管理员变更',
                    original_vip_name: '后台管理设置',
                    comment: '管理员变更',
                    vip_expire: data.vip_expire,
                    original_vip_expire: data.original_vip_expire,
                    vip_type: data.vip_type,           //会员类型
                    lvl: data.changeLvl,               //变动等级
                    original_lvl: data.original_lvl,   //变动前的积分
                    vip_sid: data.userVipInfo.vip_sid,
                    app_sid: data.userVipInfo.app_sid,
                    duration: 0,
                    cost: 0,
                    price: 0,
                };
                connection.query('INSERT INTO vip_log set ? ', [vipLogInfo], function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if(result.affectedRows > 0){
                        callback(null,'继续');
                        return;
                    }
                    callback('操作失败');
                });
            },

            function (vipInfo, callback) {
                if (!vipInfo) {
                    callback('操作失败', null);
                    return;
                }//到这里说明修改user_vip表成功，log下
                var adminLog = {
                    uid: data.userVipInfo.uid,
                    adm_uid: data.adm_uid,
                    type: 4,
                    account: data.account,
                    detail: '管理员修改用户VIP: app_sid:' + data.userVipInfo.app_sid + ',vip_sid:'
                    + data.userVipInfo.vip_sid + ',lvl:' + data.userVipInfo.uid + ',end_time:' + data.userVipInfo.end_time
                };
                connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                        if (data.userVipInfo.app_sid == 'usuz' && data.userVipInfo.vip_sid == 'xqkNoBind') {
                            addAccASWxIdToRedis({uid:data.userVipInfo.uid,account:data.account},function () {});
                        }
                    }
                });
            }
        });

    });

}

function addAccASWxIdToRedis(data,cb) {
    var param = {};
    param.app_time = new Date().getTime();
    param.account = data.account;
    param.uid = data.uid;
    param.app_sid = 'xqk';
    param.app_key = 'usuz';
    param.app_sign = getAppSign(param.app_key,GlobalVar.apps[param.app_key],param.app_time);
    baseRequest('http://' + Config.USUZHost, '/users/saveAccASWxIdToRedis', param, function(err, result){
        if(err) {
            console.log('addRealUserAndMoney err:' + err);
        }
        console.log(result);
    });
}

adminUserDao.checkVipInfo = function (data, cb) {

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        connection.query('SELECT * FROM app_vip_item WHERE id = ? AND status = 1 ',
            [data.id],
            function (err, result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }
                var itemInfo = (result && result[0]) ? result[0] : undefined;
                if (!itemInfo) {
                    cb('该购买项目不存在');
                    connection.release();
                    return;
                }
                connection.query('SELECT * FROM user_vip WHERE uid = ? AND app_sid = ? AND vip_sid = ? ',
                    [data.uid, itemInfo.app_sid, itemInfo.vip_sid],
                    function (err, result) {
                        if (err) {
                            cb(err);
                            connection.release();
                            return;
                        }
                        var res = {
                            itemInfo: itemInfo,
                            vipInfo: (result && result[0]) ? result[0] : undefined
                        }
                        cb(null, res);
                        connection.release();
                    });
            });
    });
}

//查询订单
adminUserDao.orderList = function (data, cb) {

    if (!data) return cb(new Error(500));

    var sql = 'SELECT a.*,b.account,b.name FROM order_list a LEFT JOIN users b ON a.uid = b.uid ';
    var value = [];

    if (data.app_sid) {
        sql += 'WHERE a.app_sid = ? ';
        value.push(data.app_sid);
    }

    if (data.uid) {
        sql += value.length > 0 ? 'AND a.uid = ? ' : 'WHERE a.uid = ? ';
        value.push(data.uid);
    }

    if (data.account) {
        sql += value.length > 0 ? 'AND b.account = ? ' : 'WHERE b.account = ? ';
        value.push(data.account);
    }

    if (data.status) {
        sql += value.length > 0 ? 'AND a.status = ? ' : 'WHERE a.status = ? ';
        value.push(data.status);
    }

    if (data.startTime && data.endTime) {
        data.startTime += ' 00:00:00';
        data.endTime += ' 23:59:59';
        sql += value.length > 0 ? 'AND a.created_time >= ? AND a.created_time <= ? ' : 'WHERE a.created_time >= ? AND a.created_time <= ? ';
        value.push(data.startTime);
        value.push(data.endTime);
    } else if (data.startTime) {
        var startTime = data.startTime + ' 00:00:00';
        var endTime = data.startTime + ' 23:59:59';
        sql += value.length > 0 ? 'AND a.created_time >= ? AND a.created_time <= ? ' : 'WHERE a.created_time >= ? AND a.created_time <= ? ';
        value.push(startTime);
        value.push(endTime);
    }
    sql += ' order by created_time';
    var pageNum = data.pageNum ? data.pageNum : 10;
    var page = data.page ? data.page : 1;
    sql += ' LIMIT ' + (page - 1) * pageNum + ',' + pageNum;
    DBFactory.poolQuery(sql, value,
        function () {
            cb("no connection");
        },
        function (err, result) {
            if (err) {
                cb(err, null);
                return;
            }
            if (result) {
                cb(null, result);
            }
        });
}

function getUserVipsInfo(userInfos, data) {
    var userVips = [];
    for (var i = 0; i < userInfos.length; i++) {
        var theData = userInfos[i];
        userVips.push(userVipsInfoColumn(theData, data));
    }
    return userVips;
}

function getVipLogsInfo(userInfos, data) {
    var vipLogs = [];
    for (var i = 0; i < userInfos.length; i++) {
        var theData = userInfos[i];
        vipLogs.push(vipLogsInfoColumn(theData, data));
    }
    return vipLogs;
}

function getAdminLogsInfo(userInfos, data) {
    var adminLogs = [];
    for (var i = 0; i < userInfos.length; i++) {
        var theData = userInfos[i];
        adminLogs.push(adminLogsAddInfoColumn(theData, data));
    }
    return adminLogs;
}

function getDelAdminLogsInfo(data) {
    var adminLogs = [];
    data.uids.split(',').forEach(function (uid) {
        adminLogs.push(adminLogsDelInfoColumn(uid, data));
    });
    return adminLogs;
}

function uservipsColumnNames() {
    return "`uid`,`account`,`app_sid`,`vip_sid`,`lvl`," +
        "`created_time`,`end_time`,`vip_type`";
}

function vipLogsColumnNames() {
    return "`seller_account`,`client_account`,`vip_name`,`vip_type`,`lvl`," +
        "`duration`,`cost`,`vip_expire`," +
        "`original_vip_name`," +
        "`comment`,`price`,`app_sid`,`original_lvl`,`sign`,`vip_sid`";
}

function adminLogsColumnNames() {
    return "`uid`,`adm_uid`,`account`,`type`," +
        "`detail`,`app_sid`";
}

function userVipsInfoColumn(theData, data) {

    var userVip = [];
    if (theData.uid) userVip.push(theData.uid);
    if (theData.account) userVip.push(theData.account);
    if (data.userVipInfo.app_sid) userVip.push(data.userVipInfo.app_sid);
    if (data.userVipInfo.vip_sid) userVip.push(data.userVipInfo.vip_sid);
    if (data.userVipInfo.lvl) userVip.push(data.userVipInfo.lvl);
    userVip.push(simpleDateFormat(new Date()));
    userVip.push(data.userVipInfo.end_time);
    userVip.push(data.vip_type);

    return userVip;
}

function vipLogsInfoColumn(theData, data) {

    var vipLogInfo = [];
    vipLogInfo.push('srv');
    vipLogInfo.push(theData.account);
    vipLogInfo.push('管理员变更');
    vipLogInfo.push(data.vip_type);
    vipLogInfo.push(data.userVipInfo.lvl);
    vipLogInfo.push(0);
    vipLogInfo.push(0);
    vipLogInfo.push(data.userVipInfo.end_time);
    if(data.vip_type == '1'){
        vipLogInfo.push('平台奖励积分');
        vipLogInfo.push('认证成功，平台奖励'+data.userVipInfo.lvl+'个积分');
    }else {
        vipLogInfo.push('后台管理设置');
        vipLogInfo.push('管理员变更');
    }
    vipLogInfo.push(0);
    vipLogInfo.push(data.userVipInfo.app_sid);
    vipLogInfo.push(0);
    vipLogInfo.push(0);
    vipLogInfo.push(data.userVipInfo.vip_sid);

    return vipLogInfo;
}

function adminLogsAddInfoColumn(theData, data) {

    var adminLogInfo = [];
    adminLogInfo.push(theData.uid);
    adminLogInfo.push(data.adm_uid);
    adminLogInfo.push(data.adm_account);
    adminLogInfo.push(4);
    adminLogInfo.push('管理员添加用户VIP: app_sid:' + data.userVipInfo.app_sid +
        ',vip_sid:' + data.userVipInfo.vip_sid + ',lvl:' + data.userVipInfo.lvl +
        ',end_time:' + data.userVipInfo.end_time);
    adminLogInfo.push(data.userVipInfo.app_sid);

    return adminLogInfo;
}

function adminLogsDelInfoColumn(uid, data) {

    var adminLogInfo = [];
    adminLogInfo.push(uid);
    adminLogInfo.push(data.adm_uid);
    adminLogInfo.push(data.adm_account);
    adminLogInfo.push(4);
    adminLogInfo.push('管理员删除用户VIP:' + data.app_sid + ':' + data.vip_sid);
    adminLogInfo.push(data.app_sid);

    return adminLogInfo;
}


adminUserDao.updateUserAppStatus = function (data, cb) {

    if (!data) return cb(new Error(500));

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            function (callback) {
                var sql = data.uid ? 'SELECT account FROM user_app_new_agent WHERE app_sid = ? AND uid = ? ' :
                    'SELECT uid FROM user_app_new_agent WHERE app_sid = ? AND account = ? '; //uid和account必有其一
                var value = data.uid ? [data.app_sid,data.uid] : [data.app_sid,data.account];
                connection.query(sql, value,
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if(result && result.length > 0){

                            if(data.uid) data.account = result[0].account;
                            if(data.account) data.uid = result[0].uid;
                            callback(null,'继续');
                            return;
                        }
                        callback('操作失败');
                    });
            },

            function (res,callback) {
                var userAppAgentInfo = {
                    status: data.status
                }
                if(data.comment) userAppAgentInfo.comment = data.comment;
                connection.query('UPDATE user_app_new_agent SET ? WHERE app_sid = ? AND uid = ? ', [userAppAgentInfo,data.app_sid,data.uid],
                    function (err, result) {
                        if (err) {
                            callback(err, null);
                            return;
                        }
                        if(result.affectedRows > 0){
                            callback(null, '继续');
                            return;
                        }
                        callback('操作失败');
                    });
            },

            function (res, callback) {
                if (!res) {
                    callback('操作失败', null);
                    return;
                }
                //到这里说明修改user_app_new_agent表成功，log下
                var adminLog = {
                    uid: data.uid,
                    adm_uid: data.adm_uid,
                    type: 4,
                    account: data.adm_account,
                    detail: data.status == 1 ? '管理员启用用户产品： ' + data.app_sid  : '管理员禁用用户产品： ' + data.app_sid
                };
                connection.query('insert into admin_log set ? ', adminLog, function (err, result) {
                    if (err) {
                        callback(err, null);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, '操作成功');
                    } else {
                        callback('操作失败', null);
                        console.log('操作admin_log表失败')
                    }
                });
            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}

adminUserDao.updateUserVips = function (data, cb) {
    if (!data) {
        cb(new Error(500));
        return;
    }
    getUidByAccounts(data,function (err,result) {
        if (err) {
           cb(err);
           return;
        }
        data.accInfo = result.accInfo;
        data.index = 0;
        loopUpdateUserVip(data,cb);
    });
};

function loopUpdateUserVip(data,cb) {
    var give_accs = data.give_accs;
    var accInfo = data.accInfo;
    var admUid = data.admUid;
    var index = data.index;
    if (index >= give_accs.length) {
        cb(null,{});
        return;
    }
    var account = give_accs[index];
    data.index ++;
    var userInfo = accInfo[account];
    var uid;
    if (userInfo && userInfo.uid) uid = userInfo.uid;
    if (!uid) {
        cb('用户:' + account + '未注册，请检查后再试');
        return;
    }
    var param = {};
    var userVipInfo = {
        uid:uid,
        app_sid: data.app_sid,
        vip_sid: data.vip_sid,
    };
    userVipInfo.lvl = data.lvl ? data.lvl : 0;
    if(data.endTime) userVipInfo.end_time = data.endTime;
    param.userVipInfo = userVipInfo;
    param.adm_uid = admUid;
    param.account = account;
    adminUserDao.updateUserVip(param,function (err,result) {
        if (err) {
            cb(err);
            return;
        }
        setTimeout(function () {
            loopUpdateUserVip(data,cb);
        },500);
    });
}


function getUidByAccounts(data,cb) {
    var sql = 'SELECT account,uid FROM user_app_new_agent WHERE app_sid = ? AND account IN ( ? )';
    var value = [data.app_sid,data.give_accs];
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            var accInfo = {};
            result.forEach(function (userInfo) {
                accInfo[userInfo.account] = userInfo;
            });
            cb(null, {accInfo:accInfo});
        }
    );
}
